package models

import (
	"context"
	"github.com/ethereum/go-ethereum/common"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"token-for-token/global"
)

//{
//"_id": ObjectId("66a0cc99831f00002c003387"),
//"chainName": "CHINA",
//"chainId": Long("556688"),
//"collectAddress": "CHINA",
//"FeeAddress": "CHINA",
//"userId": "669099fc022863fa5c0edf27",
//"chainConfigId": "21321312"
//}

type ChainUserConfig struct {
	Id             primitive.ObjectID   `bson:"_id ,omitempty"`
	ChainName      string               `bson:"chainName"`
	ChainId        int64                `bson:"chainId"`
	CollectAddress string               `bson:"collectAddress"`
	FeeAddress     string               `bson:"feeAddress"`
	UserId         string               `bson:"userId"`
	ChainConfigId  string               `bson:"chainConfigId"`
	Rate           primitive.Decimal128 `bson:"rate"`
	BusinessId     string               `bson:"businessId"`
}

func (c *ChainUserConfig) GetChainUserConfig() ([]ChainUserConfig, error) {

	var chainUserConfigList []ChainUserConfig
	// 获取所有数据
	cur, err := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_user_config").Find(context.Background(), bson.M{})
	if err != nil {
		return chainUserConfigList, err
	}
	err = cur.All(context.Background(), &chainUserConfigList)
	if err != nil {
		return chainUserConfigList, err
	}
	return chainUserConfigList, nil
}

// 根据CollectAddress判断是否存在
func (c *ChainUserConfig) GetChainUserConfigForCollectAddress(address string) error {
	user := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_user_config")
	filter := bson.M{"collectAddress": common.HexToAddress(address).Hex()}
	err := user.FindOne(context.Background(), filter).Decode(&c)
	return err
}

// 根据chainConfigId UserId判断是否存在
func (c *ChainUserConfig) GetChainUserConfigForChainIdUserId(chainConfigId string, userId string) error {
	user := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_user_config")
	filter := bson.M{"chainConfigId": chainConfigId, "userId": userId}
	err := user.FindOne(context.Background(), filter).Decode(&c)
	return err
}
